#include<iostream>
#include<queue>
#include<unordered_map>
using namespace std;

string s;
string anw = "123804765";
unordered_map<string, int> mp;
int dx[]={0, 0, 1, -1};
int dy[]={1, -1, 0, 0};
void bfs()
{
	
	queue<string> q;
	q.push(s);
	mp[s]=0;
	while(q.size())
	{
		string s=q.front(); q.pop();
		
		int pos=0;
		while(s[pos] != '0') pos++;
		
		
		int x=pos/3, y=pos%3;
		for(int k=0; k<4; k++)
		{
			int i=x+dx[k], j=y+dy[k];
			if(i<0 || j<0 || i>2 || j>2) continue;
			int newpos=i*3+j;
			string news=s;
			swap(news[pos], news[newpos]);
			if(mp.count(news)) continue;
			
			mp[news]=mp[s]+1;
			if(news==anw) return ;
			q.push(news);
		}
	}
	
	
}

int main()
{
	cin>>s;
	bfs();
	cout<<mp[anw]<<endl;
	return 0;
}
